package com.cqndt.disaster.device.converter;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class ConverterRegister implements InitializingBean, ApplicationContextAware {


    private Map<Integer, DeviceMessageConverter> converterMap = new HashMap<Integer, DeviceMessageConverter>();

    private ApplicationContext applicationContext;

    @Override
    public void afterPropertiesSet() throws Exception {
        Map<String, DeviceMessageConverter> beanMap = applicationContext.getBeansOfType(DeviceMessageConverter.class);

        for(DeviceMessageConverter converter : beanMap.values()){
            Integer type = converter.getDeviceType();
            converterMap.put(type, converter);
        }

    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    /**
     * 根据
     * @param type
     * @return
     */
    public DeviceMessageConverter getConverterByType(Integer type){
        return converterMap.get(type);
    }
}
